var scripts = [null, '../assets/js/bootstrap-multiselect.js', "../assets/js/jquery.validate.js", "../assets/js/jquery.validate_msgzh.js", '../assets/js/bootstrap-tagsinput.js', null]
/**
 * focusIDs 积分商品焦点图
 * detailIDs 积分商品详情图
 * */
var focusIDs = [], detailIDs = [];
$('.page-content-area').ace_ajax('loadScripts', scripts, function () {

  renderClassifyType('classifyType');

  getData();

  $("#update").click(function () {
      updateGoods();
  })

  $("#webuploader-pick").click(function () {
    resourceModel(1, 1, 11, function (data) {
      $(".mainImg").attr("src", data[0].src);
      $(".mainImg").attr("data-id", data[0].id);
      getImageWidth(data[0].src, function (w, h) {
        $("#Imgsize").html(w + '*' + h)
      });
    })
  })



  /**积分商品焦点图*/
  $("#webuploader-pick-focus").click(function () {
    resourceModel(2, 1, 11, function (data) {

      $.each(data, function (key, val) {
        if ($.inArray(val.id, focusIDs) == -1) {
          focusIDs.push(val.id);
          var html = '<li class="item">' +
            ' <div class="thumb">' +
            '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
            '<span onclick="delGoodsImg(this,1)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
            '</div>' +
            '</li>'
          $(".imgslist-focus").append(html)
        }
      })
    })
  })

  /**点击选择积分商品详情图*/
  $("#webuploader-pick-detail").click(function () {
    resourceModel(2, 1, 11, function (data) {

      $.each(data, function (key, val) {
        if ($.inArray(val.id, detailIDs) == -1) {
        	detailIDs.push(val.id);
          var html = '<li class="item">' +
            ' <div class="thumb">' +
            '<img  data-id="' + val.id + '"' + 'src="' + val.src + '">' +
            '<span onclick="delGoodsImg(this,2)" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
            '</div>' +
            '</li>'
          $(".imgslist-detail").append(html)
        }
      })
    })
  })

  /**
   * 产品属性和对应标签
   */
  var $pairs = $('#pairs');
  var $addPair = $('#addPair');

  // 点击添加按钮添加行
  $addPair.click(function (e) {
    $pairs.append(pairTemplate);
  });

  // 点击行末的"清空"按钮删除整行
  $pairs.on('click', '.btn-clear', function (e) {
    $(this).parents('.pair').remove();
  });
  // 点击标签右侧的"叉号"删除该标签
  $pairs.on('click', '.tag .close', function (e) {
    $(this).parents('.tag').remove();
  });
  // 文本框输入标签按回车后添加新标签并清空文本框
  $pairs.on('keypress', '.field-text', function (e) {
    e.stopPropagation();
    var $this = $(this);
    var $tags = $this.parents('.pair').find('.tags');
    var val = $this.val().replace(/\s/g, '');
    if (e.keyCode === 13) {
      e.preventDefault();
      var hasSameTag = (function () {
        for (var i = 0, len = $tags.find('.tag').length; i < len; i++) {
          var $tag = $tags.find('.tag').eq(i);
          var tagVal = $tag.text().replace(/\s/g, '').replace(/x$/, '');
          if (tagVal === val) {
            return true
          }
        }
        return false
      })();
      // 若有相同标签则不重复添加
      if (!hasSameTag && !!val) {
        $tags.append('<span class="tag">' + $this.val() + '<button type="button" class="close">x</button></span>');
        // 清空输入框内的文本
        $this.val('');
      }
    }
  })

  function getData() {
    var url=$utils.ajax.setUrl("store/goods/getGoodsById");
    var params={}
    params.goodsId=$utils.string.getQueryParam("id")
    axios.post(url, params)
      .then(function (response) {
        renderGoods(response.body)
      })
      .catch(function (error) {
      });
}

function renderGoods(body) {
    $("#classifyType").val(body.CLASSIFY_ID);  //区域类型
    $("#goodsCode").val(body.GOODS_CODE);
    $("#goodsName").val(body.GOODS_NAME);
    $("#goodsSum").val(body.GOODS_SUM);//国内国外
    $("#goodsRemainNum").val(body.GOODS_REMAIN_NUM);
    $("#goodsIntegral").val(body.GOODS_INTEGRAL);
    $("#goodsDetail").val(body.GOODS_DETAIL);
    $("#goodsType").val(body.GOODS_TYPE);

    var resourceImg = body.IMAGE_RESOURCES;
    if (resourceImg.length > 0) {
        var htmlfocus = ''
        var htmldetail = ''
        $.each(resourceImg, function (key, val) {
          if(val.GOODS_PIC_TYPE == 1){
        	$(".mainImg").attr("src", val.IMAGE_URL);
        	$(".mainImg").attr("data-id", val.RESOURCE_ID);

        	getImageWidth(val.IMAGE_URL,function(w,h){
        		$("#Imgsize").html(w+'*'+h)
        	});
          } else if (val.GOODS_PIC_TYPE == 2) {
            focusIDs.push(String(val.RESOURCE_ID))
            htmlfocus += '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.RESOURCE_ID + '"' + 'src="' + val.IMAGE_URL + '">' +
              '<span onclick="delGoodsImg(this,' + 1 + ')" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
          } else if (val.GOODS_PIC_TYPE == 3) {
        	detailIDs.push(String(val.RESOURCE_ID))
            htmldetail += '<li class="item">' +
              ' <div class="thumb">' +
              '<img  data-id="' + val.RESOURCE_ID + '"' + 'src="' + val.IMAGE_URL + '">' +
              '<span onclick="delGoodsImg(this,' + 2 + ')" class="btn btn-sm btn-white"> <icon class="ace-icon glyphicon glyphicon-remove red"></icon>删除</span>' +
              '</div>' +
              '</li>'
          }
        })
        $(".imgslist-focus").html(htmlfocus)
        $(".imgslist-detail").html(htmldetail)
      }

    var url = $utils.ajax.setUrl("/store/item/getItemAll");
  	axios.post(url, {})
  		.then(function (response) {
  		var itemConfList = response.body;
  		var html = ''
  		$.each(itemConfList, function (key, val) {
  		    html += '<option value="' + val.ITEM_ID + '">' + val.ITEM_NAME + '</option>'
  		});
  		pairTemplate = pairTemplate1 + html +pairTemplate2;
  		//初始化已设置的数据项
  		var itemList = body.ITEM_LIST;
        if (itemList.length > 0) {
      	  $.each(itemList, function (key, item) {
      		// 页面刚加载后就添加一行
      		var itemHtml = '';
      		$.each(itemConfList, function (key, val) {
      			if(val.ITEM_ID == item.GOODS_ITEM_ID){
      				itemHtml += '<option value="' + val.ITEM_ID + '" selected>' + val.ITEM_NAME + '</option>'
      			}else{
      				itemHtml += '<option value="' + val.ITEM_ID + '">' + val.ITEM_NAME + '</option>'
      			}
      		});
      		var tagsHtml = '';
      		var values = item.GOODS_ITEM_VALUE.split(",");
      		for (i=0;i<values.length ;i++ ){
      			tagsHtml += '<span class="tag">' + values[i] + '<button type="button" class="close">x</button></span>';
      		}
      		$pairs.append(pairTemplate1 + itemHtml +getPairTemplate2(tagsHtml));
      	  });
        }
  	});

  }

  function updateGoods() {
    var params = {}
    params.goodsId = $utils.string.getQueryParam("id");
    params.classifyId = $("#classifyType").val();
    params.goodsCode = $("#goodsCode").val();
    params.goodsName = $("#goodsName").val();
    params.goodsSum = $("#goodsSum").val();
    params.goodsRemainNum = $("#goodsRemainNum").val();
    params.goodsIntegral = $("#goodsIntegral").val();
    params.goodsDetail = $("#goodsDetail").val();
    params.goodsType = $("#goodsType").val();
    params.resourceId = $(".mainImg").attr("data-id");

    var regp = /\D/g;
    if (params.goodsCode.length == 0) {
        bootbox.alert("商品编码不能为空")
        return false
    }
    if (params.goodsName.length == 0) {
        bootbox.alert("商品名称不能为空")
        return false
    }
    if (params.goodsSum.length == 0) {
        bootbox.alert("商品总数量不能为空")
        return false
    }
    if (params.goodsRemainNum.length == 0) {
        bootbox.alert("商品库存量不能为空")
        return false
    }
    if (params.goodsIntegral.length == 0) {
        bootbox.alert("商品兑换积分不能为空")
        return false
    }
    
    if (params.goodsCode.length > 100) {
        bootbox.alert("商品编码长度不能超过100字")
        return false
    }
    if (params.goodsName.length > 100) {
        bootbox.alert("商品名称长度不能超过100字")
        return false
    }
    if (params.goodsSum.match(regp)) {
        bootbox.alert("商品总数量只能输入数字")
        return false
    }
    if (params.goodsRemainNum.match(regp)) {
        bootbox.alert("商品库存量只能输入数字")
        return false
    }
    if (params.goodsIntegral.match(regp)) {
        bootbox.alert("商品兑换积分只能输入数字")
        return false
    }
    if (params.goodsDetail.length > 200) {
        bootbox.alert("商品描述长度不能超过200字")
        return false
    }

    if (focusIDs.length > 0) {
      params.resourceGoodsIds = focusIDs.join(",")
    } else {
    	bootbox.alert("请选择商品焦点图")
        return false
    }
    if (detailIDs.length > 0) {
      params.resourceGoodsDeatilIds = detailIDs.join(",")
    } else {
    	bootbox.alert("请选择商品详情图")
        return false
    }

    if ($utils.string.isNull(params.resourceId) || params.resourceId == undefined ) {
      bootbox.alert("请选择商品主图")
      return false
    }
    
    var itemList = [];
    var itemArray = [];
    var isFail = false;
    var errorMsg = "";
    $("select[name='itemId']").each(function(j,item){
    	var stext = $("select[name='itemId']").eq(j).find("option:selected").text();
    	//判断数据项是否已经存在
    	if(itemArray.indexOf(item.value)>=0){
    		isFail = true;
    		errorMsg = "数据项:"+stext+" 不能重复设置";
    	}
    	itemArray.push(item.value);
    	
    	var itemParam = {};
    	itemParam.itemId = item.value;
    	var itemValue = "";
    	var tags = $('.pair').eq(j).find('.tags');
    	var tagsLen = tags.find('.tag').length;
    	if(tagsLen>20){
    		isFail = true;
    		errorMsg = "数据项:"+stext+" 标签数量不能超过20个。";
    	}
    	for (var i = 0, len = tagsLen; i < len; i++) {
    		var tag = tags.find('.tag').eq(i);
	        var tagVal = tag.text();
	        if(i == 0){
	        	itemValue += tagVal.substr(0,tagVal.length-1);
	        }else{
	        	itemValue += ","+tagVal.substr(0,tagVal.length-1);
	        }
    	}
    	if ($utils.string.isNull(itemValue)) {
    		isFail = true;
    		errorMsg = "数据项:"+stext+" 不能为空。";
    	}
    	if (itemValue.length>200) {
    		isFail = true;
    		errorMsg = "数据项:"+stext+" 所有标签总字数不能超过200字。";
    	}
    	itemParam.itemValue = itemValue;
    	itemList.push(itemParam);
    });
    if(isFail){
    	alert(errorMsg);
    	return false
    }
    params.itemList = itemList;

    var url = $utils.ajax.setUrl("store/goods/saveOrUpdateGoods");
    axios.post(url, params)
      .then(function (response) {
        bootbox.alert(response.msg);
          window.location.href = "#page/store/goods/list"
      })
  }



});



function delGoodsImg(obj, type) {
	  $(obj).parents(".item").remove()
	  if (type == 1) {
		  removeArrItem(focusIDs, $(obj).prev("img").attr("data-id"))
	  }
	  if (type == 2) {
		  removeArrItem(detailIDs, $(obj).prev("img").attr("data-id"))
	  }
}

var pairTemplate = "";
var pairTemplate1 = ''+
'<div class="pair">'+
	'<div class="row">'+
    	'<div class="col-xs-12">'+
  			'<form action="javascript:void(0);" class="form-inline">'+
  				'<div class="col-sm-9">'+
      				'<select class="form-control width-20" name="itemId">';
var pairTemplate2 = ''+
      				'</select>'+
      				'<div class="inline">'+
      					'<div class="tags" style="width: auto; border: none;">'+
      					'</div>'+
        			'</div>'+
        			'<input name="itemValue" type="text" class="form-control width-15 field-text" placeholder="输入标签后回车添加" value="">'+
        		'</div>'+
        		'<div class="col-sm-3">'+
      				'<button class="btn btn-sm btn-danger btn-clear">'+
      					'<i class="ace-icon fa fa-trash-o bigger-120"></i>删除'+
      				'</button>'+
      			'</div>'+
      		'</form>'+
      	'</div>'+
	'</div>'+
	'<div class="space-4"></div>'+
'</div>';

function getPairTemplate2(tags) {
	var pairTemplate2 = ''+
	      				'</select>'+
	      				'<div class="inline">'+
	      					'<div class="tags" style="width: auto; border: none;">'+tags+
	      					'</div>'+
	        			'</div>'+
	        			'<input name="itemValue" type="text" class="form-control width-15 field-text" placeholder="输入标签后回车添加" value="">'+
	        		'</div>'+
	        		'<div class="col-sm-3">'+
	      				'<button class="btn btn-sm btn-danger btn-clear">'+
	      					'<i class="ace-icon fa fa-trash-o bigger-120"></i>删除'+
	      				'</button>'+
	      			'</div>'+
	      		'</form>'+
	      	'</div>'+
		'</div>'+
		'<div class="space-4"></div>'+
	'</div>';
	return pairTemplate2;
}

